<template>
    <div class="container">
        <h1 class="title">编码组管理</h1>
        <div v-show="!isShow">
            <!-- 新建编码组和修改编码组 -->
            <div class="card-container">
                <el-card class="box-card">
                    <h3>新建编码组</h3>
                    <el-form @submit.prevent="createEncodeGroup" class="form-container">
                        <el-form-item label="新建编码组名称:" :error="newEncodeNameError">
                            <el-input v-model="newEncodeName" autocomplete="off" />
                        </el-form-item>
                        <el-form-item class="button-center">
                            <el-button type="primary" native-type="submit" style="margin-left: 40%;">创建</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>

                <el-card class="box-card">
                    <h3>修改编码组</h3>
                    <el-form @submit.prevent="updateEncodeGroup" class="form-container">
                        <el-form-item label="编码组名称:" :error="encodeIdError">
                            <el-autocomplete v-model="encodeId" :fetch-suggestions="querySearch" placeholder="修改前名称"
                                @select="handleSelect"></el-autocomplete>
                        </el-form-item>
                        <el-form-item label="修改后新名称:" :error="newputEncodeNameError">
                            <el-input v-model="newputEncodeName" autocomplete="off" />
                        </el-form-item>
                        <el-form-item class="button-center">
                            <el-button type="primary" native-type="submit" style="margin-left: 40%;">修改</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </div>

            <!-- 录入编码和删除编码组 -->
            <div class="card-container">
                <el-card class="box-card">
                    <h3>录入编码组</h3>
                    <el-form @submit.prevent="addEncode" class="form-container">
                        <el-form-item label="编码名称:" :error="encodeNameError">
                            <el-autocomplete v-model="encodeName" :fetch-suggestions="querySearch" placeholder="修改前名称"
                                @select="handleSelect"></el-autocomplete>
                        </el-form-item>
                        <el-form-item class="button-center">
                            <el-button type="primary" native-type="submit" style="margin-left: 35%;">录入编码</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>

                <el-card class="box-card">
                    <h3>删除编码组</h3>
                    <el-form class="form-container">
                        <el-form-item label="删除编码组名称:" :error="deleteEncodeIdError">
                            <el-autocomplete v-model="deleteEncodeId" :fetch-suggestions="querySearch"
                                placeholder="修改前名称" @select="handleSelect"></el-autocomplete>
                        </el-form-item>
                        <el-form-item class="button-center">
                            <el-button type="danger" native-type="submit" style="margin-left: 32%;"
                                @click="showDeleteDialog">删除编码组</el-button>
                        </el-form-item>
                    </el-form>
                    <el-dialog title="确认删除" v-model="dialogVisible" width="30%" 
                        @cancel="cancelDelete">
                        <span>你确定要删除{{ deleteEncodeId }}编码组吗？</span>
                        <span class="dialog-footer">
                            <el-button @click="cancelDelete">取消</el-button>
                            <el-button type="primary" @click="deleteEncodeGroup">确定</el-button>
                        </span>
                    </el-dialog>
                </el-card>
            </div>

            <!-- 查看编码组 -->
            <div class="view-button">
                <el-button @click="addviewEncodeGroups">查看编码组</el-button>
            </div>
        </div>
        <div class="container-id" v-if="isShow">
            <div class="left-panel">
                <el-table :data="filteredEncodeGroups" style="width: 100%">
                    <el-table-column prop="id" label="编码ID">
                        <template #default="scope">
                            <div class="table-cell-hover">{{ scope.row.id }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="名称">
    <template #default="scope">
        <el-popover
            placement="right"
            trigger="click"
            :width="600" 
            :visible="scope.row.popoverVisible"
            @show="handlePopoverShow(scope.row)"
            @hide="handlePopoverHide(scope.row)"
        >
            <template #reference>
                <div class="table-cell-hover">{{ scope.row.name }}</div>
            </template>
            <el-table :data="scope.row.groupedData" style="width: 100%;">
                <el-table-column prop="level" label="分值" align="center"></el-table-column>
                <el-table-column label="内容" align="left">
                    <template #default="scopeInner">
                        <div class="content-wrapper" :style="contentWrapperStyle(scopeInner.row.contents.length)">
                            <div v-for="(content, index) in scopeInner.row.contents" :key="index" class="content-item" :class="{ 'is-ellipsis': isEllipsis(index, scopeInner.row.contents.length) }">
                                {{ content }}
                            </div>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </el-popover>
    </template>
</el-table-column>
                </el-table>
                <el-button type="primary" @click="isShow = false">关闭查看</el-button>
            </div>
            <div class="right-panel">
                <el-input label="搜索" v-model="searchQuery" placeholder="请输入搜索内容" @input="filterEncodeGroups"></el-input>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();

const newEncodeName = ref('');//新建编码组名称
const encodeId = ref('');//修改编码组ID
const encodeName = ref('');//录入编码名称
const deleteEncodeId = ref('');//删除编码组ID
const encodeGroups = ref([]);//编码组列表
const newputEncodeName = ref('');//修改编码组名称
const oldputencodeid = ref('');//提交到后端的

const isShow = ref(false);//控制查看编码组按钮的显示与隐藏

const dialogVisible = ref(false);//控制删除编码组弹窗的显示与隐藏

const detailedInfoVisible = ref(false);//控制详细信息显示

const token = localStorage.getItem('adminToken');

// 表单验证错误信息
const newEncodeNameError = ref('');
const encodeIdError = ref('');
const encodeNameError = ref('');
const deleteEncodeIdError = ref('');
const newputEncodeNameError = ref('');

const searchQuery = ref('');//搜索内容
const filteredEncodeGroups = ref([]);//过滤后的编码组列表
filteredEncodeGroups.value = [...encodeGroups.value];

//新增加编码组
const createEncodeGroup = async () => {
    if (!newEncodeName.value.trim()) {
        newEncodeNameError.value = '编码组名称不能为空';
        return;
    }
    const newencodeName = { name: newEncodeName.value };
    try {
        const response = await axios.post('http://back1.idcfengye.com:15173/teamproject/encode', newencodeName, {
            method: 'POST',
            headers: {
                Authorization: `Bearer ${token}`,
                'Content-Type': 'application/json'
            },
        });
        if (response.status == 200) {
            ElMessage.success('编码组创建成功');
            newEncodeName.value = '';
            viewEncodeGroups();
        }
    } catch (error) {
        console.log('Error:', error);

        ElMessage.error('创建编码组失败', error.message);
    }
};

//修改编码组
const updateEncodeGroup = async () => {
    if (oldputencodeid.value == '' || newputEncodeName.value == '') {
        ElMessage.error('编码组名称和修改后的编码组名称不能为空');
        return;
    }
    try {
        const response = await axios.put(`http://back1.idcfengye.com:15173/teamproject/encode/${oldputencodeid.value}`, { name: newputEncodeName.value }, {
            headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${token}`
            },
        });
        console.log(response);

        if (response.status == 200) {
            ElMessage.success('编码组修改成功');
            encodeId.value = '';
            newputEncodeName.value = '';
            viewEncodeGroups();
        }
    } catch (error) {
        ElMessage.error(error.response.data.error);
    }
};

//跳转到录入编码的界面
const addEncode = async () => {
    if (!encodeName.value) {
        ElMessage.error('请先选择编码组');
        return;
    }
    if(!oldputencodeid.value){
        ElMessage.error('请先选择编码组(您这是不存在的编码组)');
        return;
    }
    router.push({ path: '/admin/applicationDetail', query: { id: oldputencodeid.value, name: encodeName.value } });
};

// 删除编码组
const deleteEncodeGroup = async () => {
    if (!deleteEncodeId.value.trim()) {
        deleteEncodeIdError.value = '编码组ID不能为空';
        return;
    }
    try {
        const response = await axios.delete(`http://back1.idcfengye.com:15173/teamproject/encode/${oldputencodeid.value}`, {
            headers: { Authorization: `Bearer ${token}` }
        });

        if (response.status == 200) {
            ElMessage.success('编码组删除成功');
            deleteEncodeId.value = '';
            viewEncodeGroups();
            dialogVisible.value = false; // 隐藏对话框  
        }
    } catch (error) {
        console.error('Error:', error);
        ElMessage.error('删除编码组失败');
    }
};

// 获取所有编码组
const viewEncodeGroups = async () => {
    try {
        const response = await axios.get('http://back1.idcfengye.com:15173/teamproject/encode', {
            headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${token}`
            }
        }
        );
        if (response.status == 200) {
            encodeGroups.value = response.data;           
        }
    } catch (error) {
        console.error('Error:', error);
        ElMessage.error('查看编码组失败,重新登录尝试');
    }
};

// 查看每个编码组
viewEncodeGroups();

//查看所有编码组表单显示控制
function addviewEncodeGroups() {
    viewEncodeGroups();
    filteredEncodeGroups.value=encodeGroups.value;
    isShow.value = true
}


//筛选编码组名称
function querySearch(queryString, cb) {
    viewEncodeGroups();
    // 当没有输入时，返回所有组  
    const results = queryString ?
        encodeGroups.value.filter(group => group.name.toLowerCase().includes(queryString.toLowerCase())) :
        encodeGroups.value;

    // 调用回调函数，传递筛选后的结果  
    cb(results.map(item => ({ value: item.name })));
}

//填写编码组名字后拿到id
function handleSelect(item) {
    encodeGroups.value.map(group => {
        if (group.name === item.value) {
            oldputencodeid.value = group.id
        }
    })
}

//删除编码组显示对话框  
function showDeleteDialog() {
    dialogVisible.value = true; // 显示对话框  
}

// 删除编码组隐藏对话框  
function cancelDelete() {
    dialogVisible.value = false; // 隐藏对话框  
}

// 计算悬浮窗的位置
function contentWrapperStyle(count) {
    // 你可以根据实际情况调整这个值
    const itemWidth = 400;
    // 计算容器宽你可以根据实际情况调整
    const containerWidth = 900;
    // 计算每行应该显示的内容项数量
    const itemCount = Math.floor(containerWidth / itemWidth);
    // 返回样式对象
    return {
        '--item-count': itemCount,
    };
}

// 根据索引判断是否显示省略号
function isEllipsis(index, totalCount) {
    // 如果索引大于每行显示的数量减去1，则应该显示省略号
    return index > contentWrapperStyle(totalCount)['--item-count'] - 1;
}
// 筛选编码组渲染页面
function filterEncodeGroups() {
    if (searchQuery.value) {
        filteredEncodeGroups.value = encodeGroups.value.filter(item =>
            item.name.toLowerCase().includes(searchQuery.value.toLowerCase())
        );
    } else {
        filteredEncodeGroups.value = [...encodeGroups.value];
    }
}


// handlePopoverShow 函数中
const handlePopoverShow = async (row) => {
  if (!row.groupedData || row.groupedData.length === 0) {
    row.loading = true;
    try {
      const response = await axios.get(`http://back1.idcfengye.com:15173/teamgroup/applicationlevel/encode/${row.id}`, {
        headers: {
          Authorization: `Bearer ${token}`
        }
      });
      if (response.status === 200) {
        if (response.data.data && response.data.data.length > 0) {
          const everyEncodeGroup = response.data.data;
          row.groupedData = getGroupedData(everyEncodeGroup);
        } else {
          ElMessage.warning('该编码组没有数据');
          row.groupedData = [];
        }
      } else {
        ElMessage.error('获取数据失败');
        row.groupedData = [];
      }
    } catch (error) {
      console.error('Error fetching data for row ID:', row.id, error);
      ElMessage.error('Error fetching data');
      row.groupedData = [];
    } finally {
      row.loading = false;
    }
  }
};

// popover隐藏时清理数据
const handlePopoverHide = (row) => {
    row.groupedData = [];
};

// 计算分组数据
const getGroupedData = (data) => {
    const result = {};
    let maxContentCount = 0;
    data.forEach(item => {
        const { score, content, code } = item;
        const levelKey = `(${score})`;
        if (!result[levelKey]) {
            result[levelKey] = { level: levelKey, contents: [] };
        }
        result[levelKey].contents.push(`${content}(${code})`);
        maxContentCount = Math.max(maxContentCount, result[levelKey].contents.length);
    });
    for (const key in result) {
        while (result[key].contents.length < maxContentCount) {
            result[key].contents.push('');
        }
    }
    return Object.values(result);
};

</script>

<style>
.container {
    font-family: Arial, sans-serif;
    text-align: center;
    margin: 0 auto;
    max-width: 1200px;
    position: relative;
}

.title {
    margin-bottom: 20px;
}

.box-card {
    flex: 1;
    min-width: 300px;
    /* 设置卡片的最小宽度 */
    margin: 10px;
}

.card-container {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    gap: 20px;
}

.form-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 100%;
    /* 确保表单容器占满整个卡片宽度 */
}

.button-center {
    display: flex;
    justify-content: center;
    /* 保持按钮水平居中 */
    /* 移除垂直居中的 margin，因为 el-form-item 通常已经处理了内容对齐 */
}

.el-button {
    margin: 10px 0;
    /* 添加上下外边距 */
}

.view-button {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

.encode-list {
    margin-top: 20px;
    text-align: left;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .card-container {
        flex-direction: column;
        align-items: center;
    }
}

.table-cell-hover {
    /* 您可以为悬停时的单元格添加自定义样式 */
    transition: background-color 0.3s;
    white-space: normal;
    /* 允许内容换行 */
    word-wrap: break-word;
    /* 在长单词或 URL 上换行 */
    /* 或者使用 overflow-wrap: break-word; */
}

.table-cell-hover:hover {
    background-color: #f5f7fa;
    /* 示例：悬停时改变背景色 */
}

.el-popover .el-table {
    width: 100%;
    table-layout: fixed;
}

.el-table {
    width: 100%;
    /* 或者设置为其他合适的值 */
    max-width: 100%;
    /* 防止内容溢出容器 */
    table-layout: fixed;
    /* 固定列宽，但内容可以换行 */
}

.popup {
      max-width: 100%; /* 确保气泡不会超出容器宽度 */
    box-sizing: border-box;
    width: 600px;
}

.popup.fade-transition {
    opacity: 1;
    pointer-events: auto;
    /* 恢复点击事件 */
}

.container-id {
    display: flex;
    flex-direction: row;
    height: 100%;
}

.left-panel {
    flex: 1;
    padding: 10px;
    box-sizing: border-box;
}

.right-panel {
    flex: 0 1 300px;
    /* 固定宽度或最小宽度 */
    padding: 10px;
    margin: 35% 0 0 0;
    margin-left: auto;
    /* 确保始终位于右侧 */
    box-sizing: border-box;
}

.table-cell-hover {
    cursor: pointer;
    transition: background-color 0.3s;
}

.table-cell-hover:hover {
    background-color: #f5f7fa;
}

.content-wrapper {
    overflow-x: auto; /* 添加横向滚动条 */
}
.content-item {
    white-space: normal; /* 允许换行 */
    word-break: break-all;
}
</style>
